import avatar from '@/assets/avatar.ico';
import { delSingleComment, getArticleComment } from '@/services/comments';
import { CommentInfo } from '@/services/comments/typing.d';
import { convertTimeZone } from '@/utils/operateTime';
import { Avatar, Button, Card, message, Popconfirm, Tag } from 'antd';
import { useEffect, useState } from 'react';

type Props = {
  articleId: number;
};

type ItemProps = {
  commentInfo: CommentInfo;
  refreshList: () => void;
};

const ComementItem: React.FC<ItemProps> = ({ commentInfo, refreshList }) => {
  function deleteSingleComment(commentId: number) {
    delSingleComment(commentId).then((res) => {
      message.success(res.msg);
      refreshList();
    });
  }

  return (
    <div style={{ marginBottom: '12px' }}>
      <div style={{ marginBottom: '8px' }}>
        <Avatar src={avatar} size={30} style={{ marginRight: '10px' }} />
        <span style={{ marginRight: '10px' }}>
          {commentInfo.comment_nickname}
        </span>
        <span style={{ marginRight: '10px', color: 'gray' }}>
          {convertTimeZone(commentInfo.create_time)}
        </span>
        {commentInfo.parent_id ? (
          <Tag color="geekblue">子评论</Tag>
        ) : (
          <Tag color="red">父评论</Tag>
        )}
      </div>
      <div style={{ marginLeft: '20px' }}>
        <span style={{ marginRight: '10px' }}>{commentInfo.comment}</span>
        <Popconfirm
          title={`确认删除该${commentInfo.parent_id ? '子' : '父'}评论吗？`}
          description={!commentInfo.parent_id && '删除父评论同时会删除其子评论'}
          onConfirm={() => deleteSingleComment(commentInfo.comment_id)}
          okText="Yes"
          cancelText="No"
        >
          <Button color="danger" variant="text">
            删除
          </Button>
        </Popconfirm>
      </div>
    </div>
  );
};

const CommentTree: React.FC<Props> = ({ articleId }) => {
  const [commentTree, setCommentTree] = useState<CommentInfo[]>([]);

  async function getList() {
    const res = await getArticleComment(articleId);
    setCommentTree(res.data.list);
  }

  useEffect(() => {
    getList();
  }, []);

  return (
    <>
      {commentTree.map((item) => (
        <Card style={{ marginBottom: '10px' }} key={item.comment_id}>
          <ComementItem commentInfo={item} refreshList={getList} />
          {item.replies?.map((sonComment) => (
            <div style={{ marginLeft: '60px' }} key={sonComment.comment_id}>
              <ComementItem commentInfo={sonComment} refreshList={getList} />
            </div>
          ))}
        </Card>
      ))}
    </>
  );
};

export default CommentTree;
